<?php
namespace Api\Controller;
use Think\Controller;
class CarSpiderController extends CommonController {
	public function brand(){
		$url = "https://m.chemm.com/trade/api/brands";
		$res = $this->ihttp_get($url);
		$td = json_decode($res, true);
		foreach ($td['brands'] as $key => $value) {
			foreach ($value as $k => $v) {
				$new['brand_id'] = $v['id'];
				$new['name'] = $v['name'];
				$new['letter'] = $v['letter'];
				$new['display'] = $v['display'];
				$new['logo'] = $v['thumb'];
				// M("CarBrand")->add($new);
			}
		}
	}

	// public function get_brands(){
	// 	$map['openid'] = I('openid');
	// 	$eq['shop_id'] = M("Shop")->where($map)->getField('shop_id');

	// 	$list = M("CarShopBrand")->where($eq)->select();
	// 	foreach ($list as $key => $value) {
	// 		# code...
	// 	}
	// }
	public function get_car(){
		$id = $_GET['id'];
		$detail = S("cardetail{$id}");
		dump($detail);

		// $this->ajaxReturn($detail);
	}
	public function get_car_list(){
		$id = $_GET['id'];
		$carid = $_GET['carid'];
		$td = $this->get_car_detail($id);
		// dump($td);
		$list = array();
		foreach ($td['car_detail']['list'] as $key => $value) {
			foreach ($value['groups'] as $k => $v) {
				$v['name'] = $v['style_name'];
				$v['sub_id'] = $id;
				S("cardetail{$v['id']}", $v);
				$list[] = $v;
			}
		}
		foreach ($list as $key => $value) {
			$list[$key]['carid'] = $carid;
		}
		$this->ajaxReturn($list);
	}

	private function get_car_detail($id){
		$detail = S("car{$id}");
		if(!$detail){
			$url = "https://m.chemm.com/trade/api/car_detail?id={$id}&type=trade";
			$res = $this->ihttp_get($url);
			$detail = json_decode($res, true);
			S("car{$id}", $detail, 3600*24*30);
		}
		return $detail;
	}
	public function get_sub_brand(){
		$id = $_GET['id'];
		$carid = $_GET['carid'];
		$list = S("carsubbrand{$id}");
		if(!$list){
			$url = "https://m.chemm.com/trade/api/sub_brands_new?id={$id}";
			$res = $this->ihttp_get($url);
			$td = json_decode($res, true);

			$list = array();
			foreach ($td['models'] as $key => $value) {
				foreach ($value['group'] as $k => $v) {
					$v['logo'] = $v['thumb'];
					$list[] = $v;
				}
			}
			S("carsubbrand{$id}", $list, 3600*24*30);
		}
		foreach ($list as $key => $value) {
			$list[$key]['carid'] = $carid;
		}
		$this->ajaxReturn($list);
	}
}